<template>
    <div>
      <el-dialog width="80%" title="选择商品" :visible.sync="addProductVisible" append-to-body class="dialog"
        @close="handleClose">
        <template slot="title">
          <span
            style="color: rgba(52, 69, 99, 1); font-size: 18px; font-weight: bold; margin-left: 5px; margin-top: 34px;">
            选择商品
          </span>
          <br /><br />
          <hr />
        </template>
        <div class="dialog-content">
          <search-box :tableDataInput="tableData" placeholder="请输入关键词搜索" style="width:40%;"
            @search="handleSearch">
            <template #prefix>
              <i class="el-icon-search"></i>
            </template>
          </search-box>
          <el-table :data="gridData" @selection-change="handleSelectionChange" ref="productTable">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column property="pic" label="商品图片" width="150">
              <template #default="scope">
                <el-image style="width: 50px; height: 50px" :src="scope.row.pic ? scope.row.pic : ''"></el-image>
              </template>
            </el-table-column>
            <el-table-column property="commodityName" label="商品名称" width="200"></el-table-column>
            <el-table-column property="productCategoryId" label="商品分类"></el-table-column>
            <el-table-column property="brandName" label="商品品牌"></el-table-column>
            <el-table-column property="productSn" label="货号"></el-table-column>
          </el-table>
          <el-pagination background layout="->,prev, pager,next,total" :page-size="3" :total="tableDataLength"
            @current-change="handleCurrentChange" style="margin-top: 20px;">
          </el-pagination>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="info" @click="addProductVisible = false"
            style="font-size: 14px; height: 38px; margin-right: 8px; width: 150px;">
            取消
          </el-button>
          <el-button @click="addProduct"
            style="background-color: rgba(90, 52, 179, 1); color: white; width: 150px;">
            确定
          </el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { getAllProducts, getProductDetils } from '@/api/api.js';
  
  export default {
    props: {
      dialogVisible: {
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
        addProductVisible: this.dialogVisible,
        tableDataLength: 0,
        currentPageNumber: 1,
        input: '',
        gridData: [],
        selectedIds: [], // 初始化 selectedIds
        selectedItems: {}, // 用于存储每页选择的商品项
        receiptData: [], // 初始化 receiptData
        tags: [],
        tableData: [],
        commoditydetail: {
          name: '',
          pageNo: 1,
        }
      };
    },
    async created() {
      await this.refreshPage();
    },
    methods: {
      handleClose() {
        this.$emit('update:dialogVisible', false); // 发送事件以更新父组件的 prop
        this.selectedIds = []; // 重置 selectedIds
        this.selectedItems = {}; // 重置 selectedItems
        this.$refs.productTable.clearSelection(); // 清空表格选项
      },
      async getAllProductsList() {
        try {
          const res = await getAllProducts(this.commoditydetail);
          if (res.data.code === 200) {
            this.gridData = res.data.result.records;
            this.tableData = res.data.result.records;
            this.tableDataLength = res.data.result.total;
  
            console.log('获取到的商品数据:', this.gridData);
            console.log('当前页码:', this.currentPageNumber);
            console.log('已选择的商品项:', this.selectedItems);
  
            // 恢复当前页已选择的项
            this.$nextTick(() => {
              const selected = this.selectedItems[this.currentPageNumber] || [];
              selected.forEach(item => {
                const row = this.gridData.find(row => row.id === item.id);
                console.log('正在检查恢复选择:', item, row);  // 添加调试信息
                if (row) {
                    
                  this.$refs.productTable.toggleRowSelection(row, true);
                }
              });
            });
          }
        } catch (error) {
          console.log(error);
        }
      },
      handleCurrentChange(val) {
        // 保存当前页已选择的项
        this.selectedItems[this.currentPageNumber] = [...this.$refs.productTable.selection];
        this.currentPageNumber = val;
        this.commoditydetail.pageNo = val;
        this.getAllProductsList(val);
      },
      async refreshPage() {
        await this.getAllProductsList(this.commoditydetail);
        this.currentPageNumber = 1;
      },
      handleSearch(name) {
        this.commoditydetail.name = name;
        this.refreshPage();
      },
      handleSelectionChange(selection) {
        this.selectedIds = selection.map(row => row.id);
        this.selectedItems[this.currentPageNumber] = [...selection];
        this.tags = selection.map(row => ({
          name: row.commodityName,
          details: {
            ...row,
            id: row.id,
          }
        }));
        console.log("选择的id", this.selectedIds);
        console.log("tags", this.tags);
      },
      async addProduct() {
    try {
        // Merge all selected items from different pages
        const allSelectedItems = Object.values(this.selectedItems).flat();
        const allSelectedIds = allSelectedItems.map(item => item.id);
        console.log('所有选择的商品项:', allSelectedItems);

        const productDetailsPromises = allSelectedIds.map(id => getProductDetils(id));
        const results = await Promise.all(productDetailsPromises);
        console.log("result", results);

        const updatedTags = results.flatMap((res, index) => {
            const stockList = res.data.result.spSkuStockList;
            console.log("allSelectedItems => ")
            console.log(allSelectedItems)
            if (Array.isArray(stockList)) {
                return stockList.map(stock => {
                    const spData = JSON.parse(stock.spData || '[]');
                    const skucode = stock.skuCode
                    const commodityUnit = res.data.result.commodityUnit
                    const details = {
                        ...allSelectedItems[index].details,
                        ...spData.reduce((acc, { key, value }) => {
                            acc[key] = value;
                            return acc;
                        }, {})
                    };
                    return {
                        ...allSelectedItems[index],
                        skucode,
                        details,
                        commodityUnit
                    };
                });
            } else {
                return [];
            }
        });

        console.log("目标tags", updatedTags);
        this.$emit('updateTags', updatedTags);
        this.addProductVisible = false;
    } catch (error) {
        console.log(error);
    } finally {
        this.selectedIds = []; // Reset selectedIds
        this.selectedItems = {}; // Reset selectedItems
        this.$refs.productTable.clearSelection(); // Clear table selection
    }
},
    },
    watch: {
      dialogVisible(newVal) {
        this.addProductVisible = newVal;
      }
    },
  };
  </script>
  
  <style scoped>
  .dialog {
    max-height: 100vh;
    overflow-y: hidden;
    left: 15%;
    margin-top: -50px;
  }
  
  .dialog-content {
    max-height: calc(100vh - 200px);
    overflow-y: auto;
    height: 390px;
    flex: 1;
  }
  
  .el-icon-search {
    margin-top: 14px;
    width: 15px;
    margin-left: 6px;
  }
  
  .el-pagination {
    float: right;
  }
  </style>
  